package com.example.rae.order.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * 纯手写ribbon本地负载均衡
 */
@RestController
public class ExtRibbonController {

    // 从注册中心获取服务列表信息
    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private RestTemplate restTemplate;

    //接口请求数  建议使用原子计数器，因为线程安全，效率高，使用cas无锁机制
    private int reqCount;

    @GetMapping("/ribbonMember")
    public String ribbonMember() {
        // 1.获取对应服务器远程调用地址
        String url = getInstances() + "/getMember";
        System.out.println("接口url：" + url);
        // 2.使用rest方式发送请求
        String result = restTemplate.getForObject(url, String.class);
        return result;
    }

    private String getInstances() {
        List<ServiceInstance> instances = discoveryClient.getInstances("app-rae-member");
        if (CollectionUtils.isEmpty(instances)) {
            return null;
        }
        // 服务器集群数
        int instanceSize = instances.size();
        int serviceIndex = reqCount % instanceSize;
        reqCount++;
        return instances.get(serviceIndex).getUri().toString();
    }

}
